package com.ucode.hrm.service.impl;

import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.StrUtil;
import com.ucode.hrm.mapper.HrmEmployeeMapper;
import com.ucode.hrm.service.HrmEmployeeService;
import com.ucode.model.hrm.HrmEmployee;
import com.ucode.model.hrm.enums.HrmEmploymentTypeEnum;
import com.ucode.model.hrm.enums.HrmSysResultCodeEnum;
import com.ucode.tool.exception.UcodeServiceException;
import com.ucode.tool.util.IdentifyUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Collection;

@Service
public class HrmEmployeeServiceImpl implements HrmEmployeeService {

    @Resource
    private HrmEmployeeMapper hrmEmployeeMapper;

    @Override
    public HrmEmployeeMapper initMapper() {
        return hrmEmployeeMapper;
    }

    @Override
    public Long insert(HrmEmployee hrmEmployee) {
        if (ObjUtil.isNull(hrmEmployee.getId()))
            hrmEmployee.setId(IdentifyUtils.getDefaultSnowflakeId());

        if(ObjUtil.isNotNull(this.getByIdCardNumber(hrmEmployee.getIdCardNumber())))
            throw new UcodeServiceException(HrmSysResultCodeEnum.EMPLOYEE_IDENTITY_ALREADY_EXIST);

        int i = hrmEmployeeMapper.insert(hrmEmployee);
        return i > 0 ? hrmEmployee.getId() : null;
    }

    @Override
    public int update(HrmEmployee hrmEmployee) {
        HrmEmployee dbBean = hrmEmployeeMapper.selectByPrimaryKey(hrmEmployee.getId());
        if(ObjUtil.isNull(dbBean))
            return 0;

        if(StrUtil.isNotBlank(hrmEmployee.getIdCardNumber()) &&
                !ObjUtil.equals(hrmEmployee.getIdCardNumber(), dbBean.getIdCardNumber()) &&
                ObjUtil.isNotNull(this.getByIdCardNumber(hrmEmployee.getIdCardNumber())))
            throw new UcodeServiceException(HrmSysResultCodeEnum.EMPLOYEE_IDENTITY_ALREADY_EXIST);

        //离职后就解绑会员
        if(ObjUtil.equals(hrmEmployee.getEmploymentType(), HrmEmploymentTypeEnum.LEFT.getCode())){
            hrmEmployee.setMemberId(0L);
        }
        return hrmEmployeeMapper.update(hrmEmployee);
    }

    @Override
    public HrmEmployee selectBindStatusInfo(Long memberId) {
        return hrmEmployeeMapper.selectBindStatusInfo(memberId);
    }

    @Override
    public HrmEmployee selectStatusByIdentity(String realName, String idCardNumber) {
        return hrmEmployeeMapper.selectStatusByIdentity(realName, idCardNumber);
    }

    @Override
    public int bind(Long employeeId, Long memberId) {
        return hrmEmployeeMapper.bind(employeeId, memberId);
    }

    @Override
    public int updateSspMark(Collection<Long> ids, Boolean sspMark) {
        return hrmEmployeeMapper.updateSspMark(ids, sspMark);
    }

}
